//
//  MHSearchFriendsViewController.m
// MiaoCircle
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHSearchFriendsViewController.h"
#import "MHSearchMembersViewModel.h"
#import "MHCommonCell.h"
#import "MHCommonItemViewModel.h"
#import "MHCircleMember.h"
#import "MHAlertTableViewModel.h"
#import "MHAlertTableViewView.h"
#import "MHMomentViewModel.h"
@interface MHSearchMembersViewController ()<UISearchBarDelegate,UIGestureRecognizerDelegate>
/// viewModel
@property (nonatomic, readonly, strong) MHSearchMembersViewModel *viewModel;

@end

@implementation MHSearchMembersViewController

@dynamic viewModel;

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = MH_MAIN_BACKGROUNDCOLOR_2;
//    self
    /// 初始化
    [self _setup];
    
    /// 初始化子控件
    [self _setupSubViews];
    
}

#pragma mark - 绑定模型
- (void)bindViewModel{
    [super bindViewModel];
}
//- (UIEdgeInsets)contentInset{
//    return UIEdgeInsetsMake(MH_APPLICATION_TOP_BAR_HEIGHT, 0, 0, 0);
//}
//

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.viewModel.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[section];
    return groupViewModel.itemViewModels.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
    
    return [MHCommonCell cellWithTableView:tableView];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /// fetch cell
    MHCommonCell *cell = (MHCommonCell *)[self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[indexPath.section];
    id object = groupViewModel.itemViewModels[indexPath.row];
    /// bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    [cell setIndexPath:indexPath rowsInSection:groupViewModel.itemViewModels.count];
    
    cell.imageView.userInteractionEnabled = YES;
    cell.tag = indexPath.section;
    cell.imageView.tag = indexPath.row;
    __weak __typeof(self)weakSelf = self;
    @weakify(self);
    [cell.imageView bk_whenTapped:^{
        @strongify(self);
        MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[cell.tag];
        id object = groupViewModel.itemViewModels[cell.imageView.tag];
        MHCommonItemViewModel *itemItemViewModel =  (MHCommonItemViewModel *)object;
        MHCircleMember *userMember = (MHCircleMember *)itemItemViewModel.model;
        if (![userMember isKindOfClass:[MHCircleMember class]]) {
            return ;
        }
        IMAUser *user = [[IMAUser alloc] initWith:[NSString stringWithFormat:@"%d",userMember.userId]];
        user.icon = userMember.fullUserFace;
        user.nickName = userMember.nickName;
        IMAConversation *conversation =  [[IMAPlatform sharedInstance].conversationMgr chatWith:user];
        MHMomentViewModel *viewModel = [[MHMomentViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIsFootPrint:@(true),MHViewModelTitleKey:isEquaalCurrentUserId(user.userId)?@"我的足迹":@"Ta的足迹",MHViewModelConversation:conversation}];
        viewModel.userId = [user.userId intValue];
        viewModel.imUser = user;
        [self.viewModel.services pushViewModel:viewModel animated:YES];
    }];
    return cell;
}

- (void)configureCell:(MHCommonCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object{
    MHCommonItemViewModel *model =  (MHCommonItemViewModel *)object;
    MHCircleMember *circleMember = (MHCircleMember *)model.model;
    
    if(self.viewModel.info.identType == MHCircleIdentityTypeOwner || self.viewModel.info.identType == MHCircleIdentityTypeManager)
    {
        MHAlertTableViewModel *settingManage = [MHAlertTableViewModel new];
        BOOL isManager =  (circleMember.identType == MHCircleIdentityTypeManager);
        BOOL notOwnerSelf =  (circleMember.identType == MHCircleIdentityTypeOwner);
        settingManage.titile = isManager ? @"取消管理员" : @"设置成管理员";
        __weak __typeof(self)weakSelf = self;
        settingManage.operationBlock = ^{
            if(isManager)
            {
                [[weakSelf.viewModel.cancelMemberTypeCommand execute:@(circleMember.autoId)] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeGuestMember;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }else
            {
                
                [[weakSelf.viewModel.setIdentityCommand execute:@{@"memberId":@(circleMember.autoId),@"identType":@(2)}] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeManager;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }
            
            [weakSelf.zh_popupController dismiss];
        };
        
        MHAlertTableViewModel *settingjb = [MHAlertTableViewModel new];
        BOOL isInterviewer =  (circleMember.identType == MHCircleIdentityTypeGuest);
        settingjb.titile = isInterviewer ? @"取消嘉宾":@"设为嘉宾";
        settingjb.operationBlock = ^{
            if(isInterviewer)
            {
                [[weakSelf.viewModel.cancelMemberTypeCommand execute:@(circleMember.autoId)] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeGuestMember;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }else
            {
                [[weakSelf.viewModel.setIdentityCommand execute:@{@"memberId":@(circleMember.autoId),@"identType":@(3)}] subscribeNext:^(id x) {
                    circleMember.identType = MHCircleIdentityTypeGuest;
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
            }
            
            [weakSelf.zh_popupController dismiss];
        };
        MHAlertTableViewModel *black = [MHAlertTableViewModel new];
        black.titile = @"拉黑";
        black.operationBlock = ^{
            [self showAlertViewControllerWithTitle:[NSString stringWithFormat:@"确定将 %@ 拉黑",circleMember.nickName] content:@"拉黑后,该成员将无法查看圈内消息以及发表内容" comfirmblock:^{
                [[weakSelf.viewModel.blakMemberCommand execute:@(circleMember.userId)] subscribeNext:^(id x) {
                    [self.viewModel.circleMembers removeObject:circleMember];
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
                [weakSelf.zh_popupController dismiss];
            } dissMissBlock:^{
                [weakSelf.zh_popupController dismiss];
            }];
            
            
        };
        
        MHAlertTableViewModel *remove = [MHAlertTableViewModel new];
        remove.titile = @"移除该成员";
        remove.operationBlock = ^{
            [self showAlertViewControllerWithTitle:@"移除该成员" content:@"确定移除该成员?" comfirmblock:^{
                [[weakSelf.viewModel.removeMemberCommand execute:@(circleMember.autoId)] subscribeNext:^(id x) {
                    [self.viewModel.circleMembers removeObject:circleMember];
                    [self.viewModel willChangeValueForKey:@"circleMembers"];
                    [self.viewModel didChangeValueForKey:@"circleMembers"];
                }];
                [weakSelf.zh_popupController dismiss];
            }dissMissBlock:^{
                 [weakSelf.zh_popupController dismiss];
            }];
            
        };
        
        
        if (indexPath.section == 0 && !notOwnerSelf) {
            
            
            model.operation = ^{
                if (self.viewModel.info.identType == MHCircleIdentityTypeOwner) {
                    NSMutableArray *operationPermisson = [@[settingManage,black,remove] mutableCopy];
                    if (isInterviewer) {
                        [operationPermisson insertObject:settingjb atIndex:0];
                    }
                    MHAlertTableViewView *tableView  = [[MHAlertTableViewView alloc] initWithDataSource:operationPermisson andHeaderData:circleMember];
                    tableView.width = self.view.width * 0.8;
                    weakSelf.zh_popupController = [zhPopupController new];
                    [weakSelf.zh_popupController presentContentView:tableView];
                }else
                {
//                    model.operation = ^{
                        NSMutableArray *array = [@[] mutableCopy];
                        
                        self.viewModel.info.identType == MHCircleIdentityTypeOwner ? ([array appendObjects: @[settingManage,black]] ) : ([array appendObjects:@[black]]);
                        if (isInterviewer) {
                            [array appendObject:settingjb];
                        }
                        [array appendObject:remove];
                        MHAlertTableViewView *tableView  = [[MHAlertTableViewView alloc] initWithDataSource:array andHeaderData:circleMember];
                        tableView.width = self.view.width * 0.8;
                        weakSelf.zh_popupController = [zhPopupController new];
                        [weakSelf.zh_popupController presentContentView:tableView];
//                    };
                }
            };
        }else if (indexPath.section == 1)
        {
            model.operation = ^{
                NSMutableArray *array = [@[] mutableCopy];
                
                self.viewModel.info.identType == MHCircleIdentityTypeOwner ? ([array appendObjects: @[settingManage,black]] ) : ([array appendObjects:@[black]]);
                if (isInterviewer) {
                    [array appendObject:settingjb];
                }
                [array appendObject:remove];
                MHAlertTableViewView *tableView  = [[MHAlertTableViewView alloc] initWithDataSource:array andHeaderData:circleMember];
                tableView.width = self.view.width * 0.8;
                weakSelf.zh_popupController = [zhPopupController new];
                [weakSelf.zh_popupController presentContentView:tableView];
            };
        }
    }
    [cell bindViewModel:object];
}


#pragma mark - 初始化
- (void)_setup{
    
}
#pragma mark - 初始化子控件
- (void)_setupSubViews{
    
}



#pragma mark - UISearchBarDelegate
// 键盘中，搜索按钮被按下，执行的方法
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    MHLogFunc;
    /// 去掉空格
    if ([NSString mh_isEmpty:searchBar.text]) return;
    [self.viewModel.searchCommand execute:searchBar.text];
    
}


#pragma mark - UISearchResultsUpdating
// Called when the search bar's text or scope has changed or when the search bar becomes first responder.
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    /// 获取输入的文字
    NSString *inputStr = searchController.searchBar.text;
    NSLog(@"inputStr is %@",inputStr);
    self.viewModel.searchText = inputStr;
    
    
    
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 66;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}




@end
